
package com.scalar.chiptrack.operations.proformainvoice.actions;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.packingslip.PackingSlipComparator;
import com.scalar.chiptrack.operations.proformainvoice.BankInfo;
import com.scalar.chiptrack.operations.proformainvoice.dao.ProFormaInvoiceDAO;
import com.scalar.chiptrack.operations.proformainvoice.forms.ProFormaInvoiceForm;
import com.scalar.chiptrack.sales.LineItem;
import com.scalar.chiptrack.sales.SalesOrder;
import com.scalar.chiptrack.sales.actions.SalesOrderAction;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.users.User;


public final class ProFormaInvoiceAction extends ChipTrackAction {

    private static final String ACTION_NAME = "/proFormaInvoice.do";

    public ActionForward execute (ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response)
                                  throws Exception {


        HashMap errors = new HashMap();
        request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);

        HashMap info = new HashMap();
        request.setAttribute (SessionKeys.INFO_MESSAGES, info);

        HttpSession session = request.getSession();
		boolean value = false;
        User user = (User) session.getAttribute (SessionKeys.USER_KEY);
       /* if (user == null) {
            session.setAttribute (SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString());
            return (mapping.findForward ("login"));
        }*/
        //modified by varma 15 sep 2004
        String action = request.getParameter ("action");
        if (user == null) {
            if( action.startsWith( "loadInvoice" ) || "saveBankInfo".equalsIgnoreCase( action ) ) {
                session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME );
            }
            else {
                session.setAttribute (SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString() );
            }
            return ( mapping.findForward ( "login" ) );
        }

        ProFormaInvoiceForm proFormaInvoiceForm = (ProFormaInvoiceForm) form;
        String bankName = null;
		String address = null;
		String city = null;
		String state = null;
		String zipcode = null;
		String country = null;
		String abaValue = null;
		String acct = null;
		String swiftcode = null;
		BankInfo bankInfo = new BankInfo();
        //String action = request.getParameter ("action");
        int salesOrderid = proFormaInvoiceForm.getSalesOrderId();
		//System.out.println("action "+action  +"salesOrderid  "+salesOrderid );

	    if( "ConfirmToDeleteInvoice".equalsIgnoreCase( action ) == true ) {
            int salesOrderId = -1;
            try {
				String flag = request.getParameter("Flag");
				String salesId = request.getParameter("salesOrderId");
				//System.out.println("flag "+flag);
				if( salesId != null)
				salesOrderId = Integer.parseInt(request.getParameter("salesOrderId"));
				if("True".equals(flag))
				request.setAttribute("setConfirm","Yes");
				loadSalesOrderDetails(request,errors,salesOrderId);
            }
            catch( ScalarException se ) {
                errors.put( "Internal Server Error", "Could not delete the Pro-Forma Invoice");
                se.getRootCause().printStackTrace();
                System.out.println( "Could not delete the invoice for Sales Order ID: " + salesOrderId );
            }
			try {
				bankInfo = ProFormaInvoiceDAO.loadBankInfo(salesOrderId);
				if( bankInfo != null)
				request.setAttribute("BankInfo",bankInfo);
			}
            catch(ScalarException e) {
                e.printStackTrace();
            }

        }
	    //Added by Sarada on 15th Dec 2003 to delete invoice after co
		if( "deleteInvoice".equalsIgnoreCase( action ) == true ) {
            int salesOrderId = -1;
            try {
				String salesId = request.getParameter("salesOrderId");
				//System.out.println("salesId "+salesId);
				if( salesId != null)
				salesOrderId = Integer.parseInt(request.getParameter("salesOrderId"));
                ProFormaInvoiceDAO.deleteInovice( salesOrderId );
                info.put( "Pro-Forma Invoice has been deleted, successfully", null );
            }
            catch( ScalarException se ) {
                errors.put( "Internal Server Error", "Could not delete the Pro-Forma Invoice");
                se.getRootCause().printStackTrace();
                System.out.println( "Could not delete the invoice for Sales Order ID: " + salesOrderId );
            }
        }
		if("CancelPage".equals(action)) {
			int salesOrderId = -1;
			try {
                String salesId = request.getParameter("salesOrderId");
                //System.out.println("salesId in Cancel "+salesId);
                if( salesId != null) {
                    salesOrderId = Integer.parseInt(request.getParameter("salesOrderId"));
                    loadSalesOrderDetails(request,errors,salesOrderId);
                    bankInfo = ProFormaInvoiceDAO.loadBankInfo(salesOrderId);
                    if( bankInfo != null)
                        request.setAttribute("BankInfo",bankInfo);
                }
			}
            catch( ScalarException se ) {
                errors.put( "Internal Server Error", "Could not delete the Pro-Forma Invoice");
                se.getRootCause().printStackTrace();
                System.out.println( "Could not delete the invoice for Sales Order ID: " + salesOrderId );
            }
			//return (mapping.findForward("success"));
        }
        // Invoice view - same window
        if( ( action != null ) && ( action.startsWith( "loadInvoice" ) ) )
        {
            int salesOrderId = -1;
            if( "loadInvoice".equalsIgnoreCase( action ) ) {
                if( "true".equalsIgnoreCase( request.getParameter( "bySalesOrderNumber" ) ) ) {
                    salesOrderId = SalesOrderDAO.getSalesOrderIdbyNumber( proFormaInvoiceForm.getSalesOrderNumber() );
                    if( salesOrderId == -1 ) {
                        errors.put( "Invalid Sales Order Number: " + proFormaInvoiceForm.getSalesOrderNumber(), null );
                    }
                }
                else {
                    salesOrderId = proFormaInvoiceForm.getSalesOrderId();
					boolean result = checkSalesOrderNo(""+salesOrderId);
				    if(result == true) {
						request.setAttribute("DELETE","True");
					}
			    }
           }
           else if( "loadInvoiceByDeletedInvoiceSalesOrderId".equalsIgnoreCase( action ) ) {
                request.setAttribute( "DELETED_INVOICE", "true" );
                salesOrderId = proFormaInvoiceForm.getDeletedInvoiceSalesOrderId();
           }
           int isSample = Integer.parseInt( SalesOrderDAO.getOrderType( null, salesOrderId ) );
           if ( isSample < 2 ) {
                loadSalesOrderDetails(request,errors,salesOrderId);
           }
           else {
                errors.put( "Invalid Sales Order Number: " + proFormaInvoiceForm.getSalesOrderNumber(), null );
           }

           try {
                bankInfo = ProFormaInvoiceDAO.loadBankInfo(salesOrderId);
                if( bankInfo != null)
                request.setAttribute("BankInfo",bankInfo);
           }
           catch(ScalarException e) {
               e.printStackTrace();
           }
       }
       //Added by Sarada on 14th Nov 2003 to save BankInfo
       if( "saveBankInfo".equalsIgnoreCase( action ) ) {
            //Added by Sarada on 2nd Dec 2003 to get correct salesOrderId
            int salesOrderId1 = -1;
            int salesOrderId2 = -1;
            int salesOrderId = proFormaInvoiceForm.getSalesOrderId();
            salesOrderId1 = SalesOrderDAO.getSalesOrderIdbyNumber( proFormaInvoiceForm.getSalesOrderNumber() );
            salesOrderId2 = proFormaInvoiceForm.getDeletedInvoiceSalesOrderId();

            if(salesOrderId == -1 && salesOrderId2 == -1) {
                salesOrderId = salesOrderId1;
            }

            else  if(salesOrderId == -1  && salesOrderId1 == -1) {
               salesOrderId = salesOrderId2;
            }
            loadSalesOrderDetails(request,errors,salesOrderId);
            bankName = proFormaInvoiceForm.getBankName();
            address = proFormaInvoiceForm.getAddress();
            city = proFormaInvoiceForm.getCity();
            state = proFormaInvoiceForm.getState();
            zipcode = proFormaInvoiceForm.getZipCode();
            country = proFormaInvoiceForm.getCountry();
            abaValue = proFormaInvoiceForm.getAba();
            acct = proFormaInvoiceForm.getAcct();
            swiftcode = proFormaInvoiceForm.getSwiftCode();
            try {
                value = ProFormaInvoiceDAO.updateBankInfo(bankName,address,city,state,zipcode,country,abaValue,acct,swiftcode,salesOrderId);
                if(value == true)
                info.put( "Banking Information is saved successfully", null );
                else
                errors.put( "Could not save Banking Information " , null );
            }
            catch(ScalarException e){e.printStackTrace();}

            //Added by Sarada on 14th Nov 2003 to set BankInfo to printer page
            try{
                 bankInfo = ProFormaInvoiceDAO.loadBankInfo(salesOrderId);
                 if( bankInfo != null)
                 request.setAttribute("BankInfo",bankInfo);
            }
            catch(ScalarException e){e.printStackTrace();}
        }//if( "saveBankInfo".equalsIgnoreCase( action ) )


        // Invoice view - Pop-Up window
        if( "showInvoice".equalsIgnoreCase( action ) ) {
            int salesOrderId = -1;
            salesOrderId = proFormaInvoiceForm.getSalesOrderId();
            loadSalesOrderDetails(request,errors,salesOrderId);
		    //Added by Sarada on 14th Nov 2003 to set BankInfo to default page
            try{
                     bankInfo = ProFormaInvoiceDAO.loadBankInfo(salesOrderId);
                     if( bankInfo != null)
                     request.setAttribute("BankInfo",bankInfo);
            }
            catch(ScalarException e) {
                e.printStackTrace();
            }
            return (mapping.findForward ("view"));
        }
		proFormaInvoiceForm.setBankName(bankInfo.getBankName());
		proFormaInvoiceForm.setAddress(bankInfo.getAddress());
		proFormaInvoiceForm.setCity(bankInfo.getCity());
		proFormaInvoiceForm.setState(bankInfo.getState());
		proFormaInvoiceForm.setZipCode(bankInfo.getZipCode());
		proFormaInvoiceForm.setCountry(bankInfo.getCountry());
		proFormaInvoiceForm.setAba(bankInfo.getAba());
		proFormaInvoiceForm.setAcct(bankInfo.getAcct());
		proFormaInvoiceForm.setSwiftCode(bankInfo.getSwiftCode());
		request.setAttribute("proFormaInvoiceForm",proFormaInvoiceForm);
		//Sarada's code ends here
        request.setAttribute( "salesOrderList", ProFormaInvoiceDAO.loadShippingPendingSalesOrderIdAndNumberList() );
        request.setAttribute( "invoiceDeletedSalesOrderList", ProFormaInvoiceDAO.loadInvoiceDeletedSalesOrderIdAndNumberList() );
        request.setAttribute( "salesOrdercustomerPOList", ProFormaInvoiceDAO.loadShippingPendingSalesOrderCustomerPOList() );

        return (mapping.findForward ("success"));
    }


    private Object[] getShippedLineItems( int salesOrderId ,int customerId) throws ScalarException {

        // HashMap lineItemMap = SalesOrderDAO.loadOrderLineItemsMap ( salesOrderId );
	    //Modified by sarada on 28th Jan 2004 to get customer part no
        HashMap lineItemMap = SalesOrderDAO.loadOrderLineItemsWithCustomerPartNos ( salesOrderId , customerId );
        if( lineItemMap == null ) lineItemMap = new HashMap();

        Iterator lineItemsIterator = lineItemMap.values().iterator();
        String lineItemId = null;
        ArrayList resultLineItems = new ArrayList();

        LineItem lineItem = null;
        float subtotal = 0.0f;

        while (lineItemsIterator.hasNext()) {

            lineItem = (LineItem) lineItemsIterator.next();

            if (lineItem != null) {
                subtotal += lineItem.getQuantity()*lineItem.getUnitPrice();
                resultLineItems.add (lineItem);
            }
        }
        return new Object[] {resultLineItems, subtotal+""};
    }


    //Added by Sarada on 15th Dec 2003 to check the SalesOrderId related to CustomerPo is present in SalesOrderIds of Deleted Invoices

	public boolean checkSalesOrderNo(String salesOrderId)throws ScalarException
    {
		ArrayList customerPoList = new ArrayList();
		boolean flagValue = false;
		customerPoList = ProFormaInvoiceDAO.loadInvoiceDeletedSalesOrderIdAndNumberList();
		int  listSize = customerPoList.size();

			 for(int i=0;i<listSize;i++) {
				 if(flagValue == false) {
					 org.apache.struts.util.LabelValueBean customerPos = (org.apache.struts.util.LabelValueBean)customerPoList.get(i);
					 if(salesOrderId.equals(customerPos.getValue())) {
						  flagValue = true;
					 }
				 }
			 }
	    return flagValue;
    }

    //Added by Sarada on 15th Dec 2003 to optimise the code ,which is using more than once
    public void loadSalesOrderDetails(HttpServletRequest request, HashMap errors, int salesOrderId )throws ScalarException
    {
	    BankInfo bankInfo = new BankInfo();
        int customerId = 0;
        Object[] result = null;

		SalesOrder salesOrder = null;
		try {
			salesOrder = SalesOrderDAO.loadSalesOrder( salesOrderId+"" );

            // Prabhanjan (30 Mar 2004)
            // Commented by veeru on 16th June 2004
			/*if ( ! ( salesOrder.getEndUser ().trim ().equals ( "" ) ) )
            {
                int endUserId = EndUserDAO.getEndUserIdByName ( salesOrder.getEndUser (), salesOrder.getCustomerId () );
                //EndUser endUser = EndUserDAO.getEndUserDetails ( endUserId );
                //salesOrder.setBillingAddressId ( endUser.getDefaultBillingAddressId () );
                //salesOrder.setShippingAddressId ( endUser.getDefaultShippingAddressId () );
                //salesOrder.setBillingAddress ( SalesOrder.getAddressAsString ( endUser.getBillingAddress () ) );
                //salesOrder.setShippingAddress ( SalesOrder.getAddressAsString ( endUser.getShippingAddress () ) );
                //salesOrder.setBillingAddressAsObject ( endUser.getBillingAddress () );
                //salesOrder.setShippingAddressAsObject ( endUser.getShippingAddress () );

                ApproveOrderAction.loadEndUserContactPersonDetails ( salesOrder, endUserId );
            }*/

			//Added  by sarada on 28 th Jan 2004 to get customer part numbers for particular customer id
            customerId = salesOrder.getCustomerId();
            result = getShippedLineItems( salesOrderId , customerId);
            ArrayList lineItems = (ArrayList) result[0];

            // Prabhanjan (05 Mar 2004)
           /* if ( !( salesOrder.getEndUser ().trim ().equals ( "" ) ) )
            {
                int endUserId = EndUserDAO.getEndUserIdByName ( salesOrder.getEndUser (), salesOrder.getCustomerId () );
                SalesOrderDAO.loadEndUserPartNumbersForLineItems ( null, lineItems, endUserId );
            }*/
            //SalesOrderDAO.loadCustomerPartNumbersForLineItems( null, lineItems, salesOrder.getCustomerId(), salesOrder.getOdmId() );
            Collections.sort(lineItems,new PackingSlipComparator());
            request.setAttribute ("lineItems", lineItems);
			request.setAttribute ( "lineItemsWithSubtotals", SalesOrderAction.loadLineItemsWithSubTotals ( lineItems ) );

		}
		catch( ScalarException e ) {
			e.printStackTrace();
			System.out.println( "Exception while loading the salesOrder for salesOrderId: " + salesOrderId );
		}

		if( salesOrder == null ) {
			errors.put( "Could not load sales order for the sales order id: " + salesOrderId, null );
		}
		else {
			salesOrder.setSubTotal (Float.parseFloat((String) result[1]));
			request.setAttribute ("salesOrder", salesOrder);
			request.setAttribute("salesOrderId", salesOrderId+"");
		}

	    try{
		    bankInfo = ProFormaInvoiceDAO.loadBankInfo(salesOrder.getSalesOrderId());
			if( bankInfo != null)
			request.setAttribute("BankInfo",bankInfo);
		}
        catch(ScalarException e) {
            e.printStackTrace();
        }
 }
}